package amalgame.ventas;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.Dialog;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.support.v4.app.NavUtils;
import android.text.format.DateFormat;


import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import com.j256.ormlite.dao.Dao;



import amalgame.data.DataSQLiteHelper;
import amalgame.data.DatabaseManager;
import amalgame.entity.CustomAdapter;

import amalgame.entity.ListaActividad;
import amalgame.entity.db.Categorie;
import amalgame.entity.db.Customer;
import amalgame.entity.db.Product;
import amalgame.entity.db.Stock;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;


public class ProductActivity extends ListaActividad {
	ListView listView;
	List<Product> productList;
	List<String> productListStr;
	private DatabaseManager manager;
	private Context mContext;
	private ImageButton btn_categoryAdd;
	
	private String picturFile = "";
	public static String PATH_APPDIRs = "sistema_ventas";
	
	private Dialog customDialog;
	
	private ImageButton  btn_add;
	public static Product productEdit = null;
	
	
	public TextView tv_stock;
	
	public TextView tv_cantity;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.abm_product_inventory);

		Random r = new Random();
		int Max = 100;
		int Min = 1;
		int ran = r.nextInt(Max - Min + 1) + Min;
		
		
		
		mContext = getApplicationContext();
		manager = DatabaseManager.getInstance();
		
		//@+id/abm_categoryadd
		btn_categoryAdd = (ImageButton) findViewById(R.id.abm_categoryadd);
		btn_categoryAdd.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(mContext, CategoriesActivity.class);
				startActivity(intent);
				
			}
		});
		btn_add = (ImageButton) findViewById(R.id.abm_productadd);
		btn_add.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
					
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), AddProductActivity.class);
				startActivity(intent);
					
			}
		});
		
		
		// datos cargados		
		
		listView = (ListView) getListView();		
		updateList_customAdapter();
		
		 //##################################################################################################################
		 // click
		 //##################################################################################################################		 
		 listView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
					try {
						if(productList.size()<=0) return;
					
				
					}catch(Exception e){
						e.printStackTrace();
					}
				}
			});
	}
	

	private void updateList_customAdapter(){
		productList = manager.getAllproduct();
		productListStr = new ArrayList<String>();
		if (productList.size()>0){
			for (Product item : productList) {
				productListStr.add(item.getName());
				registerForContextMenu(listView);
			}
		}else		{
			productListStr.add(getResources().getString(R.string.no_item_added));
			unregisterForContextMenu(listView);
		}
		productList = manager.getAllproduct();
		CustomAdapter_product_iconrow_custom customAdapter = new CustomAdapter_product_iconrow_custom(mContext, productList);
	
		listView.setAdapter(customAdapter);
	
		
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		updateList_customAdapter();
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		//return super.onCreateOptionsMenu(menu);
		
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.add_product, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem menu) {
		// TODO Auto-generated method stub
		//return super.onOptionsItemSelected(menu);
		
		if(menu.getItemId()==R.id.menu_addproduct_categorie){
			Intent intent = new Intent();
			intent.setClass(mContext, CategoriesActivity.class);
			startActivity(intent);
			
			
			return true;
		}
		
		return false;
	}
	
	
	/**
	 * @param String message
	 * @param String title
	 * @return 
	 */
	public Dialog showDialogEliminar(String message, String title,final int ID){
			//
			
			customDialog = new Dialog(ProductActivity.this);
			customDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);			
			customDialog.setContentView(R.layout.simpledialog_okcancel);
			customDialog.setCancelable(false);		
			
			TextView tv_title =  (TextView) customDialog.findViewById(R.id.simpledialog_okcancel_title);
			TextView tv_text  = (TextView) customDialog.findViewById(R.id.simpledialog_okcancel_text);
			Button btn_ok     = (Button) customDialog.findViewById(R.id.simpledialog_okcancel_ok);
			Button btn_cancel     = (Button) customDialog.findViewById(R.id.simpledialog_okcancel_cancel);
		
			tv_title.setText(title);
			tv_text.setText(message);
			
			
			btn_ok.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					manager.deleteProductByID(ID);
					updateList_customAdapter();
					customDialog.cancel();
					//finish();
				}
			});
			
			btn_cancel.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					customDialog.cancel();
					//finish();
				}
			});
			return customDialog;
	}	
	
	
	
	
	public Dialog showDialogChooseNumber(String message, String title,final int ID){
		customDialog = new Dialog(ProductActivity.this);
		customDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);			
		customDialog.setContentView(R.layout.choosenumberdialog);
		customDialog.setCancelable(false);		
		
		final TextView tv_cantity =  (TextView) customDialog.findViewById(R.id.choosenumberdialog_textView);
		Button btn_ok     = (Button) customDialog.findViewById(R.id.choosenumberdialog_OK);
		
		Button btn_cancel     = (Button) customDialog.findViewById(R.id.choosenumberdialog_CANCEL);
	
		TextView tv_stock = (TextView) findViewById(R.id.iconrow_custom_tv_desc);
	       
		
		final SeekBar seekBarValue10 = (SeekBar)customDialog.findViewById(R.id.choosenumberdialog_seekBar10);
		
		//tv_cantity.setText(seekBarValue100.getText().toString().trim());

		
		seekBarValue10.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){

		    @Override
		    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
		    	
		    //	tv_cantity.setText(String.valueOf(seekBarValue10.getProgress() + seekBarValue100.getProgress()*10 ));
		    	tv_cantity.setText(String.valueOf(seekBarValue10.getProgress() ));
		    }
			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
			}
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
			}
		});
		

		//tv_stock.setText(message);

	
		btn_ok.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
				//Add to the stock the new add quantity
				String str_quantity = tv_cantity.getText().toString();
				int int_quantity = Integer.valueOf(str_quantity);
				Stock stock =new Stock(new Date().toString() ,productEdit.getProductId(), int_quantity);
				manager.addStock(stock);
				
				//update the new Product cantity
				int stock_quantity  = manager.getQuantityByProductId(stock.getProduct_id());
				productEdit.setQuantity(stock_quantity);
				boolean ret = manager.updateProduct(productEdit);
				
				
				if (ret) {
					Toast.makeText(mContext,
							getString(R.string.the_item_is_updated),
							Toast.LENGTH_LONG).show();
				} else {
					Toast.makeText(mContext,
							getString(R.string.failed_to_update_the_item),
							Toast.LENGTH_LONG).show();

				}
				
				updateList_customAdapter();
				customDialog.cancel();
				//finish();
			}
		});
		
		btn_cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				customDialog.cancel();
				//finish();
			}
		});
		return customDialog;
}	

	
	

	

	
	
	
	
	public class CustomAdapter_product_iconrow_custom extends BaseAdapter implements Filterable {
		 /**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		private Context mContext;
		    private int id;
		    private List <String>items ;
		    private List<Product> list_product;
	        
		    private LayoutInflater mInflater;
	        private int mViewId;

		    @SuppressWarnings("unchecked")
			public CustomAdapter_product_iconrow_custom(Context context, List<Product> productList ) 
		    {
		        //super(context, R.layout.simpleiconrow, list);
		    	//super();
		        mContext = context;
		       this.list_product = productList;
		       
		    }

		    public View getView(final int position, View v, ViewGroup parent)
		    {
		        View mView = v ;
		        if(mView == null){
		            LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		            mView = vi.inflate(R.layout.iconrow_custom, null);
		        }

		        TextView tv_title = (TextView) mView.findViewById(R.id.iconrow_custom_tv_title);		        													
		        TextView tv_stock = (TextView) mView.findViewById(R.id.iconrow_custom_tv_desc);
		        
		        ImageView   img = (ImageView) mView.findViewById(R.id.iconrow_custom_imv_pic);
		        
		        ImageButton imb_delete = (ImageButton) mView.findViewById(R.id.iconrow_custom_imb_delete);
		        ImageButton imb_edit = (ImageButton) mView.findViewById(R.id.iconrow_custom_imb_edit);
		        ImageButton imb_add = (ImageButton) mView.findViewById(R.id.iconrow_custom_imagebutton_addproduct);
		           

		        
		        
		        
		        imb_add.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						productEdit = productList.get(position);
						
						//TITTLE & TEXT
						String  title = getResources().getString(R.string.app_name);
						String text =  getResources().getString ( R.string.Add ) ;
						
						Dialog dialog = new Dialog(ProductActivity.this);
						dialog = showDialogChooseNumber(text, title,   id);						
						dialog.show();													
					}
				});
		        
		        
		        
		        if(list_product.get(position) != null )
		        {
		            tv_title.setTextColor(Color.BLACK);
		            tv_title.setText(list_product.get(position).getName());

		            tv_stock.setTextColor(Color.BLACK);
		            
		            
		            String desc = "Stock:" + list_product.get(position).getQuantity();		            
		            tv_stock.setText(desc);
		            
		            //Peter
		        	Date fecha = new Date();
					SimpleDateFormat ft = new SimpleDateFormat("yyyy_MM_dd_hhmmss");
					String fechaCompleta = ft.format(fecha);
		            
				
					
					String strPicture = list_product.get(position).getPhoto();
					try {
						if(!strPicture.equals("")){
							String strFile = Environment.getExternalStorageDirectory()+ "/" + PATH_APPDIRs  + "/" + strPicture ;
							File file = new File( strFile );
							
							System.out.println ("productactivity  foto : " + strFile);
							if(file.exists())
							{ 
								Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
								img.setImageBitmap(myBitmap);
							}
							else
							{
								
							}
						}
						
					} catch (Exception e) {
						e.printStackTrace();
					}
					
					//is not getQantity, must take the ACTUAL valor
		    		Stock stock =new Stock(fechaCompleta ,list_product.get(position).getProductId(), list_product.get(position).getQuantity());
		    		//manager.addStock(stock);
		    		//Fin Peter
		            
		            
		        }
		        
		        
		        imb_delete.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						
						productEdit = productList.get(position);
						
						// ITEM
						int id  = productList.get(position).getProductId();
						String name =  productList.get(position).getName();
						   		
						//TITTLE & TEXT
						String  title = getResources().getString(R.string.customer);
						String text =  getResources().getString ( R.string.do_you_want_to_delete_this_item_) + " " + name;
						
						Dialog dialog = new Dialog(ProductActivity.this);
						dialog = showDialogEliminar(text, title,   id);
						dialog.show();													
					}
				});
		        
		        
		        imb_edit.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						
						productEdit = productList.get(position);

						Intent intent = new Intent();
						intent.putExtra("MODE", "EDIT");
						
						
						
						intent.setClass(ProductActivity.this, AddProductActivity.class);
						startActivity(intent);
						
						
					}
				});
		        
		        //v.setBackground(mContext.getResources().getDrawable(  R.drawable.fondolist));
		        
		        return mView;
		    }

		    
		    public int getCount() {
		        return list_product.size();
		    }

		    public Object getItem(int position) {
		        return list_product.get(position);
		    }

		    public long getItemId(int position) {
		        return position;
		    }

			@Override
			public Filter getFilter() {
				  return new Filter() {

			            @SuppressWarnings("unchecked")
			            @Override
			            protected void publishResults(CharSequence constraint,
			                    FilterResults results) {
			            	list_product = (List<Product>) results.values;
			                CustomAdapter_product_iconrow_custom.this.notifyDataSetChanged();
			            }

			            @Override
			            protected FilterResults performFiltering(CharSequence constraint) {

			                List<Product> filteredResults = getFilteredResults(constraint);

			                FilterResults results = new FilterResults();

			                results.values = filteredResults;

			                return results;
			            }
			        };
			}
			protected List<Product> getFilteredResults(CharSequence constraint) {
			    ArrayList<Product> filteredList = new ArrayList<Product>(); 
			    for (Product c:list_product) { 
			        if (c.getName().trim().toLowerCase().startsWith(constraint.toString().trim().toLowerCase())) { // you can also use contains instead of startsWith...whatever you need 
			            filteredList.add(c); 
			        } 
			    } 
			    return filteredList;
			}
			
			
	
	}
}
